package com.sparrow.source.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sparrow.source.common.dto.IasUserQueryRequest;
import com.sparrow.source.common.dto.Result;
import com.sparrow.source.common.dto.UserSaveOrUpdateDto;
import com.sparrow.source.common.enums.ResultEnum;
import com.sparrow.source.common.utils.SnowflakeIdGenerator;
import com.sparrow.source.persistense.IasUser;
import com.sparrow.source.service.IIasUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bryceyung
 * @since 2024/11/20
 */
@Controller
@RequestMapping("/v1/user")
public class UserController {

    @Autowired
    private IIasUserService userService;

    private final SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(1, 1);

    @PostMapping("/query/pages")
    @ResponseBody
    public Result queryAllUserPage(@RequestBody IasUserQueryRequest queryRequest, Page<IasUser> page) {
        return Result.build(ResultEnum.SUCCESS).setObject(userService.queryUserPage(queryRequest, page));
    }

    @PostMapping("/getInfo")
    @ResponseBody
    public Result queryDetailById(@RequestParam("id") Integer id) {
        return Result.build(ResultEnum.SUCCESS).setObject(userService.getById(id));
    }

    @PostMapping("save")
    @ResponseBody
    public Result save(@RequestBody UserSaveOrUpdateDto userSaveOrUpdateDto) {
        IasUser user = new IasUser();
        user.setName(userSaveOrUpdateDto.getName());
        user.setTel(userSaveOrUpdateDto.getTel());
        user.setPersonId(snowflakeIdGenerator.nextId());
        return Result.build(ResultEnum.SUCCESS).setObject(userService.save(user));
    }

    @PostMapping("update")
    @ResponseBody
    public Result update(@RequestBody UserSaveOrUpdateDto userSaveOrUpdateDto) {
        IasUser user = new IasUser();
        user.setName(userSaveOrUpdateDto.getName());
        user.setTel(userSaveOrUpdateDto.getTel());
        user.setId(userSaveOrUpdateDto.getUserId());
        return Result.build(ResultEnum.SUCCESS).setObject(userService.updateById(user));
    }

    @PostMapping("delete")
    @ResponseBody
    public Result delete(@RequestParam("userId") Integer userId) {
        return Result.build(ResultEnum.SUCCESS).setObject(userService.delete(userId));
    }

}
